package controllers

import (
	"finance/internal/dto"
	"finance/internal/message"
	"finance/internal/models"
	"finance/internal/utils"
	"github.com/gin-gonic/gin"
	"net/http"
)

// Login @Summary User login
// @Description Login with username and password
// @Tags auth
// @Accept json
// @Produce json
// @Param login body dto.LoginRequest true "Login info"
// @Success 200 {object} dto.LoginResponse
// @Failure 400 {object} utils.Response
// @Router /api/login [post]
func Login(c *gin.Context) {
	var req dto.LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(400, gin.H{"msg": "invalid request"})
		return
	}

	user, err := models.GetUserByUsername(req.Username)
	if err != nil || !models.CheckPassword(user.Password, req.Password) {
		c.JSON(401, gin.H{"msg": message.InvalidCredential})
		return
	}

	userRole, err := models.GetUserRole(user.ID)
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"msg": message.UserRoleNotFound})
		return
	}

	token, _ := utils.GenerateToken(user.ID, user.Username, userRole.RoleName, userRole.RoleID)
	c.JSON(200, gin.H{
		"code":  200,
		"token": token,
		"msg":   "Login success",
	})
}
